#include	<stdlib.h>
#include	<stdbool.h>

#define		min(v)(v >= 'A' && v <= 'Z' ? v + 32 : v)

void		my_putchar(char c)
{
  write(1, &c, 1);
}

void		my_putstr(char *str)
{
  int		i;

  i = 0;
  while (str[i])
    my_putchar(str[i++]);
}

int		my_strlen(char *str)
{
  int		i;

  i = 0;
  while (str[i])
    i++;
  return (i);
}
bool		is_space(char c)
{
  return (c == ' ' || c == '\t');
}

void		mnstcpy(char *dest, char *src, int n)
{
  int		i;

  i = 0;
  while (src[i] && i < n)
    {
      dest[i] = src[i];
      ++i;
    }
  dest[i] = '\0';
}

int		nb_wd(char *str)
{
  int		i;
  int		j;
  int		wd;

  wd = 0;
  i = 0;
  while (str[i])
    {
      while (str[i] && is_space(str[i]))
	++i;
      j = i;
      while (str[i] && !is_space(str[i]))
	++i;
      if (i != j)
	++wd;
    }
  return (wd);
}

char		**stwt(char *str)
{
  char		**tab;
  int		i;
  int		j;
  int		wd;

  tab = malloc(nb_wd(str) * sizeof(*tab));
  wd = 0;
  i = 0;
  while (str[i])
    {
      while (str[i] && is_space(str[i]))
	++i;
      j = i;
      while (str[i] && !is_space(str[i]))
	++i;
      if (i != j)
	{
	  tab[wd] = malloc((i - j + 1) * sizeof(**tab));
	  mnstcpy(tab[wd], &str[j], i - j);
	  ++wd;
	}
    }
  tab[wd] = NULL;
  return (tab);
}

void		showt(char **tab)
{
  ssize_t	i;

  i = 0;
  while (tab[i])
    {
      my_putstr(tab[i]);
      if (tab[i] && tab[i + 1] &&
	  my_strlen(tab[i]) == my_strlen(tab[i + 1]))
	my_putchar(' ');
      else
	my_putchar('\n');
      ++i;
    }
}

int		mstcmp(char *s1, char *s2)
{
  int		i;

  i = 0;
  while (s1[i] && s2[i])
    {
      if (min(s1[i]) != min(s2[i]))
	return (min(s1[i]) - min(s2[i]));
      ++i;
    }
  return (0);
}

void		trimtab1(char **tab)
{
  int		i;
  int		j;
  char		*tmp;

  i = 0;
  while (tab[i])
    {
      j = i;
      while (j > 0 && my_strlen(tab[j]) == my_strlen(tab[j - 1]) &&
	     mstcmp(tab[j], tab[j - 1]) < 0)
	{
	  tmp = tab[j - 1];
	  tab[j - 1] = tab[j];
	  tab[j] = tmp;
	  --j;
	}
      ++i;
    }
}

void		trimtab2(char **tab)
{
  int		i;
  int		j;
  char		*tmp;

  i = 0;
  while (tab[i])
    {
      j = i;
      while (j > 0 && my_strlen(tab[j]) < my_strlen(tab[j - 1]))
	{
	  tmp = tab[j - 1];
	  tab[j - 1] = tab[j];
	  tab[j] = tmp;
	  --j;
	}
      ++i;
    }
}

void		ord_alphlong(char *str)
{
  char		**tab;

  tab = stwt(str);
  trimtab2(tab);
  trimtab1(tab);
  showt(tab);
}

int		main(int argc,char **argv)
{
  if (argc > 1)
    ord_alphlong(argv[1]);
  else
    my_putchar('\n');
  return (0);
}
